<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddRole">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table :data="rolesList" style="width: 100%" border stripe>
        <!-- 展开行 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              v-for="(item, i) in scope.row.children"
              :key="item.id"
              :class="['bd_bottom', i === 0 ? 'bd_top' : '']"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="delCurrentRight(scope.row, item.id)">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级、三级权限 -->
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  v-for="(item2, i2) in item.children"
                  :key="item2.id"
                  :class="[i2 !== 0 ? 'bd_top' : '']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="delCurrentRight(scope.row, item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      closable
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      @close="delCurrentRight(scope.row, item3.id)"
                    >{{ item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300">
          <template v-slot="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delCurrentRole(scope.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightsDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="dialogVisible" width="50%" @close="addDialogClosed">
      <el-form :model="addForm" :rules="handleFormRules" ref="addFormRef" label-width="90px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="handleFormRules" ref="editFormRef" label-width="90px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCurrentRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="rightsDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <!-- 树状组件 -->
      <el-tree
        :data="rightsList"
        :props="defaultProps"
        node-key="id"
        show-checkbox
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer">
        <el-button @click="rightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      rightsList: [],
      defKeys: [],
      // 即将分配权限的角色 id
      roleId: '',
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      editForm: {},
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      dialogVisible: false,
      editDialogVisible: false,
      rightsDialogVisible: false,
      handleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表数据
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('角色列表获取失败！')
      }

      this.rolesList = res.data
    },
    // 显示添加角色对话框
    showAddRole() {
      this.dialogVisible = true
    },
    // 添加角色
    addRole() {
      // 校验表单
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 校验成功发送请求添加用户
        const { data: res } = await this.$http.post('roles', this.addForm)

        if (res.meta.status !== 201) {
          return this.$message.error('角色添加失败！')
        }
        this.$message.success('角色添加成功！')
        // 隐藏对话框
        this.dialogVisible = false
        // 重新获取数据
        this.getRolesList()
      })
    },
    // 关闭 Dialog 对话框时执行的事件处理函数
    addDialogClosed() {
      // 重置表单
      this.$refs.addFormRef.resetFields()
    },
    // 显示编辑对话框
    async showEditDialog(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('roles/' + id)

      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败！')
      }

      this.editForm = res.data
    },
    // 编辑角色
    editCurrentRole() {
      // 先对表单进行校验
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.put(
          'roles/' + this.editForm.roleId,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc
          }
        )

        if (res.meta.status !== 200) {
          return this.$message.error('编辑角色失败')
        }

        this.$message.success('编辑用户成功！')
        // 关闭编辑对话框
        this.editDialogVisible = false
        // 重新获取数据
        this.getRolesList()
      })
    },
    // 删除角色
    async delCurrentRole(id) {
      const confirmInfo = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmInfo !== 'confirm') {
        return this.$message.info('已取消删除！')
      }

      const { data: res } = await this.$http.delete('roles/' + id)

      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败！')
      }

      this.$message.success('删除角色成功！')
      this.getRolesList()
    },
    // 关闭编辑角色对话框
    editDialogClosed() {
      // 重置表单
      this.$refs.editFormRef.resetFields()
    },
    // 删除角色单个权限
    async delCurrentRight(role, rightId) {
      // 危险操作先弹出对话框进一步确认
      const confirmInfo = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmInfo !== 'confirm') {
        return this.$message.info('已取消删除！')
      }

      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )

      if (res.meta.status !== 200) {
        return this.$message.error('角色权限删除失败！')
      }
      this.$message.success('角色权限删除成功！')
      // 调用方法重新获取权限列表，会渲染整个表格
      // this.getRolesList()

      // 通过响应数据覆盖当前角色权限，实现局部渲染
      role.children = res.data
    },
    // 显示分配权限对话框
    async showSetRightsDialog(role) {
      // 保存角色 id
      this.roleId = role.id

      // 发送请求获取权限数据
      const { data: res } = await this.$http.get('rights/tree')

      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败！')
      }
      this.rightsList = res.data
      // 获取三级权限
      this.getLeafKeys(role, this.defKeys)

      this.rightsDialogVisible = true
    },
    // 通过递归获取三级节点的 id
    getLeafKeys(node, arr) {
      // 如果当前 node 不包含 children 属性，则是三级节点，将其保存到 arr 中
      if (!node.children) {
        return arr.push(node.id)
      }
      // 包含 children 属性，再进行遍历递归调用
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 当角色对话框关闭时，清空 defKeys 数组
    setRightDialogClosed() {
      this.defKeys = []
    },
    // 为当前角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]

      const idStr = keys.join(',')

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: idStr
        }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('角色权限更新失败！')
      }

      this.$message.success('角色权限更新成功！')
      this.getRolesList()

      this.rightsDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px;
  .el-row {
    display: flex;
    align-items: center;
  }
}
.el-tag {
  margin: 7px;
}
.bd_top {
  border-top: 1px solid #eee;
}
.bd_bottom {
  border-bottom: 1px solid #eee;
}
</style>
